package com.frame.platform.menu;



import java.util.*;

import org.hibernate.*;
import com.frame.database.DataBase;
import com.frame.database.DbOperate;
import com.frame.database.JdataBean;
import com.frame.database.util.*;
import com.frame.hibernate.HibernateUtil;
import com.frame.pageform.component.tree.TreeNode;
import com.frame.platform.rank.Wfmenu;
import com.frame.util.SelectItem;

public class MenuDao {

    public int m;
    private Session session;
    private String menuStr;

    public MenuDao(){

    }
    public void addMenu(Wfmenu menu) throws Exception{
//        menu.setOrderid(new Integer(999));
//        DataBase.getInstance().save(menu);
        JdataBean bean=new JdataBean();
        bean.put("id", menu.getId());
        bean.put("name", menu.getName());
        bean.put("url", menu.getUrl());
        bean.put("orderid", 999);
        bean.put("opentype", menu.getOpenType());
        bean.put("ISREFRESH",menu.getIsRefresh());
        DbOperate.getInstance().saveBean("wfmenu", bean.getDataMap());
    }
    /**
     * 添加菜单时获得菜单主键
     * @param topId
     * @return
     * @throws Exception
     */
    public String getKeyId(String topId) throws Exception{
        int l=topId.length()+1;
        List list=DataBase.getInstance().queryBySql("select max(substring(m.id,"+l+",3)) from Wfmenu m where m.id like ?", new Object[]{topId+"___"});
        String code=topId+"001";
        if(list.size()>0){
            if(list.get(0)!=null && list.get(0).toString().length()>0){
                int n=Integer.parseInt(list.get(0).toString());
                n++;
                if(n<10)
                    code= topId+"00"+n;
                else if(n<100)
                    code= topId+"0"+n;
                else if(n>999)
                    throw new Exception("主键序列号已超过3位");
                else
                    code= topId+n;
            }
        }
        return code;
    }
    public Wfmenu getMenu(String menuId) throws HibernateException, Exception{
        return (Wfmenu)DataBase.getInstance().getBean(Wfmenu.class , menuId);
    }
    public List<SelectItem> getMenuhome(String menuId) throws HibernateException, Exception{
        Session session=HibernateUtil.currentSession();
        List<Wfmenu> list=new ArrayList<Wfmenu>();
        String m=menuId;
        while(m.length()>=6){
            Wfmenu menu=(Wfmenu)session.load(Wfmenu.class, m);
            list.add(menu);
            m=menu.getId().substring(0,m.length()-3);
        }
        List<SelectItem> mlist=new ArrayList<SelectItem>();
        for(int i=(list.size()-1);i>=0;i--)
            mlist.add(new SelectItem(list.get(i).getId(),list.get(i).getName()));

        HibernateUtil.closeSession();
        return mlist;
    }
    public void updateMenu(Wfmenu menu) throws HibernateException, Exception{
        Session session=HibernateUtil.currentSession();
        Transaction transaction=session.beginTransaction();
        Wfmenu loadmenu=(Wfmenu)session.load(Wfmenu.class, menu.getId());
        loadmenu.setName(menu.getName());
        loadmenu.setUrl(menu.getUrl());
        loadmenu.setIsRefresh(menu.getIsRefresh());
        loadmenu.setPhoto(menu.getPhoto());
        loadmenu.setOpenType(menu.getOpenType());
        loadmenu.setJavaScript(menu.getJavaScript());
        loadmenu.setState(menu.getState());
        session.flush();
        transaction.commit();
        HibernateUtil.closeSession();
    }
    public void delMenu(Wfmenu menu) throws HibernateException, Exception{
        DataBase data=DataBase.getInstance();
        data.delete("delete Wfrankmenu where id.menuid like ?",new Object[]{menu.getId()+"%"});
        data.delete("delete Wfmenu where id like ?",new Object[]{menu.getId()+"%"});
    }
    public Wfmenu findMenu(String menuName) throws HibernateException, Exception{
        DataBase data=DataBase.getInstance();
        ConditionMap map=new ConditionMap();
        map.put("name = ? ").setParameter(menuName);
        List list=data.query("Wfmenu", map);
        if(list.size()>0)
            return (Wfmenu)list.get(0);
        else
            return null;
    }
    public boolean checkUrl(String url,String menuId) throws Exception{
        if(url!=null && !"".equals(url)){
            ConditionMap map=new ConditionMap();
            map.put("url = ? ").setParameter(url);
            if(menuId!=null)
                map.put("id <> ? ").setParameter(menuId);
            List list=DataBase.getInstance().query("Wfmenu", map);
            if(list.size()>0)
                return false;
            else
                return true;
        }
        return true;
    }
    public List getSubMenu(String menuId) throws Exception{
        ConditionMap map=new ConditionMap();
        map.put("id like ?").setParameter(menuId+"___");
        map.addOrder("orderid", true);
        return DataBase.getInstance().query("Wfmenu", map);
    }
    public void sortMenu(String[] menuIds){
        Session session=HibernateUtil.currentSession();
        Transaction transaction=session.beginTransaction();
        for(int i=0;i<menuIds.length;i++){
            Wfmenu menu=(Wfmenu)session.load(Wfmenu.class, menuIds[i]);
            menu.setOrderid(new Integer(i+1));
            session.flush();
        }
        transaction.commit();
        HibernateUtil.closeSession();
    }
    /**
     *
     * 功能:查询当前账户权限子菜单<br>
     * 参数:<br>
     * 作者:王海锋<br>
     * 时间:2014-1-14 下午01:43:17<br>
     * 说明:<br>
     * 变更:<br>
     * @throws Exception
     */
    public List getRankSubMenu(String userId,String deptId,String code) throws Exception{
        String sql="";
        int length=code.length()+3;
        session=HibernateUtil.currentSession();
        Query query=null;
        List list=null;
        try{
            if(!userId.equals("0000000001")){
                sql="select m from Wfmenu m where m.id in (select substring(t.id,1,"+length+") from Wfmenu t,Wfrankmenu r,Wfuserrank u " +
                        "where t.id=r.id.menuid and r.id.rankid=u.id.rankid and u.id.userid=? and u.id.deptid in ("+deptId+") " +
                        "and t.id like ?" +
                        ") and m.state=1 order by m.orderid,m.id";
                query=session.createQuery(sql);
                query.setString(0, userId);
                query.setString(1, code+"___%");
            }
            else{
                //超级管理员
                sql="select m from Wfmenu m where m.id in (select substring(t.id,1,"+length+") from Wfmenu t where t.id like ?) and m.state=1 order by m.orderid";
                query=session.createQuery(sql);
                query.setString(0, code+"___%");
            }
            list= query.list();
        }catch(Exception e){throw e;}finally{
            HibernateUtil.closeSession();
        }
        return list;
    }
    /**
     * 查询当前账户权限所有菜单
     * @param userId
     * @param deptId
     * @return
     * @throws Exception
     */
    public void getRankMenuAll(String userId,String deptId,TreeNode pnode) throws Exception{
        String code=pnode.getId();
        int length=code.length()+3;
        String sql="";
        Query query=null;
        if(!userId.equals("0000000001")){
            sql="select m from Wfmenu m where m.id in (select substring(t.id,1,"+length+") from Wfmenu t,Wfrankmenu r,Wfuserrank u " +
                    "where t.id=r.id.menuid and r.id.rankid=u.id.rankid and u.id.userid=? and u.id.deptid in ("+deptId+") " +
                    "and t.id like ?" +
                    ") and m.state=1 order by m.orderid,m.id";
            query=session.createQuery(sql);
            query.setString(0, userId);
            query.setString(1, code+"___%");
        }
        else{
            //超级管理员
            sql="select m from Wfmenu m where m.id in (select substring(t.id,1,"+length+") from Wfmenu t where t.id like ?) and m.state=1 order by m.orderid";
            query=session.createQuery(sql);
            query.setString(0, code+"___%");
        }

        List list=query.list();
        List clist=pnode.getChildList();
        if(clist==null)
            clist=new ArrayList();
        for(int i=0;i<list.size();i++){
            Wfmenu menu=(Wfmenu)list.get(i);
            TreeNode node = new TreeNode(menu.getId(), menu
                    .getParId(), menu.getName());
//          node.setUrl(menu.getUrl());
            node.setIcon(menu.getPhoto());
            clist.add(node);
            getRankMenuAll(userId,deptId,node);
        }
        pnode.setChildList(clist);
    }
    public String initMenu(String userId,String deptId,String parMenuId,String path) throws Exception{
        session=HibernateUtil.currentSession();
        TreeNode rootNode=new TreeNode(parMenuId,"","");
        getRankMenuAll(userId,deptId,rootNode);
        HibernateUtil.closeSession();
        List list= rootNode.getChildList();
        menuStr="";
        for(int i=0;i<list.size();i++){
            TreeNode n=(TreeNode)list.get(i);
            menuStr+="<div title='"+n.getText()+"' data-options=\"";
            if(n.getIcon()!=null && !"".equals(n.getIcon()))
                menuStr+="iconUrl:'"+path+n.getIcon()+"'";
            menuStr+="\" style='padding-top:5px;'>";
            menuStr+="<ul class='easyui-tree'>";
//                menuStr+="<li id='menuid_"+n.getId()+"' data-options=\"iconUrl:'"+path+n.getIcon()+"'\"><span>"+n.getText()+"</span>";
//                menuStr+="<ul>";
            List clist=n.getChildList();
            for(int c=0;c<clist.size();c++){
                TreeNode node=(TreeNode)clist.get(c);
                getNode(node,path);
            }
//                menuStr+="</ul>";
//                menuStr+="</li>";
            menuStr+="</ul>";
            menuStr+="</div>\n";
        }
        return menuStr;
    }
    /*
    public String initMenu(String userId,String deptId,String parMenuId,String path) throws Exception{
        session=HibernateUtil.currentSession();
        TreeNode rootNode=new TreeNode(parMenuId,"","");
        getRankMenu(userId,deptId,rootNode);
        HibernateUtil.closeSession();
        List list= rootNode.getChildList();
        menuStr="";
        for(int i=0;i<list.size();i++){
                TreeNode n=(TreeNode)list.get(i);
                menuStr+="<div title='"+n.getText()+"' data-options=\"";
                if(n.getIcon()!=null && !"".equals(n.getIcon()))
                    menuStr+="iconUrl:'"+path+n.getIcon()+"'";
                menuStr+="\">";
                menuStr+="<ul class='easyui-tree'>";
                menuStr+="<li id='menuid_"+n.getId()+"' data-options=\"iconUrl:'"+path+n.getIcon()+"'\"><span>"+n.getText()+"</span>";
                menuStr+="<ul>";
                List clist=n.getChildList();
                for(int c=0;c<clist.size();c++){
                    TreeNode node=(TreeNode)clist.get(c);
                    getNode(node,path);
                }
                menuStr+="</ul>";
                menuStr+="</li>";
                menuStr+="</ul>";
                menuStr+="</div>\n";
        }
        return menuStr;
    }
    */
    private void getNode(TreeNode node,String path){
        List list=node.getChildList();
        menuStr+="<li id='menuid_"+node.getId()+"'";
        if(node.getIcon()!=null && !"".equals(node.getIcon()))
            menuStr+=" data-options=\"iconUrl:'"+path+node.getIcon()+"'\"";
        menuStr+="><span>"+node.getText()+"</span>";
        if(list.size()>0){
            menuStr+="<ul>";
            for(int i=0;i<list.size();i++){
                TreeNode n=(TreeNode)list.get(i);
                getNode(n,path);
            }
            menuStr+="</ul>";
        }
        menuStr+="</li>";
    }

}
